#pragma once

#include "kernel/dtos/map_display_dto.h"
#include <QQuickPaintedItem>
#include <QPainter>
#include <QColor>
#include <QTransform>
#include <QAbstractListModel>
// 移除QTimer头文件，不再需要定时器
#include <QSettings>

namespace presentation {

// 地图绘制配置结构
struct MapDrawingConfig {
    // 颜色配置
    QColor backgroundColor{Qt::white};
    QColor stationColor{QColor("#C9F970")};
    QColor pathColor{QColor("#409F41")};
    QColor areaColor{QColor("#FF69B4")};  // 粉红色
    QColor normalPointColor{QColor("#696969")};
    QColor stationBorderColor{QColor("#409F41")};
    
    // 尺寸配置
    double stationSize{0.7};
    double pathWidth{6.0};
    double scaleFactor{30.0};
    double normalPointSize{3.0};
    
    // 性能配置
    int normalPointSampleRate{5};  // 每5个点采样一次
    double minScaleForStationText{59.0};  // 显示站点文字的最小缩放级别
    
    // 变换配置
    double defaultScale{1.0};
    double zoomFactor{1.2};
    
    // 字体配置
    QString stationFontFamily{"Arial"};
    int stationFontSize{14};
};

class MapBackgroundItem : public QQuickPaintedItem {
    Q_OBJECT

    Q_PROPERTY(kernel::MapDisplayDto mapData READ mapData WRITE setMapData NOTIFY mapDataChanged)
    Q_PROPERTY(QAbstractListModel* agvListModel READ agvListModel WRITE setAgvListModel NOTIFY agvListModelChanged)
    Q_PROPERTY(QColor backgroundColor READ backgroundColor WRITE setBackgroundColor NOTIFY backgroundColorChanged)
    Q_PROPERTY(QColor stationColor READ stationColor WRITE setStationColor NOTIFY stationColorChanged)
    Q_PROPERTY(QColor pathColor READ pathColor WRITE setPathColor NOTIFY pathColorChanged)
    Q_PROPERTY(QColor areaColor READ areaColor WRITE setAreaColor NOTIFY areaColorChanged)
    Q_PROPERTY(double stationSize READ stationSize WRITE setStationSize NOTIFY stationSizeChanged)
    Q_PROPERTY(double pathWidth READ pathWidth WRITE setPathWidth NOTIFY pathWidthChanged)
    Q_PROPERTY(double scaleFactor READ scaleFactor WRITE setScaleFactor NOTIFY scaleFactorChanged)
    Q_PROPERTY(QPointF panOffset READ panOffset WRITE setPanOffset NOTIFY panOffsetChanged)
    Q_PROPERTY(bool showAgvLabels READ showAgvLabels WRITE setShowAgvLabels NOTIFY showAgvLabelsChanged)
    Q_PROPERTY(double agvIconSize READ agvIconSize WRITE setAgvIconSize NOTIFY agvIconSizeChanged)
    Q_PROPERTY(bool filterAgvByMap READ filterAgvByMap WRITE setFilterAgvByMap NOTIFY filterAgvByMapChanged)

    // Map dimensions for QML binding
    Q_PROPERTY(int mapWidth READ mapWidth NOTIFY mapWidthChanged)
    Q_PROPERTY(int mapHeight READ mapHeight NOTIFY mapHeightChanged)

public:
    explicit MapBackgroundItem(QQuickItem* parent = nullptr);

    // Property getters
    const kernel::MapDisplayDto& mapData() const { return mapData_; }
    QAbstractListModel* agvListModel() const { return agvListModel_; }
    QColor backgroundColor() const { return config_.backgroundColor; }
    QColor stationColor() const { return config_.stationColor; }
    QColor pathColor() const { return config_.pathColor; }
    QColor areaColor() const { return config_.areaColor; }
    double stationSize() const { return config_.stationSize; }
    double pathWidth() const { return config_.pathWidth; }
    double scaleFactor() const { return config_.scaleFactor; }
    QPointF panOffset() const { return panOffset_; }
    bool showAgvLabels() const { return showAgvLabels_; }
    double agvIconSize() const { return agvIconSize_; }
    bool filterAgvByMap() const { return filterAgvByMap_; }
    int mapWidth() const { return mapWidth_; }
    int mapHeight() const { return mapHeight_; }

    // Property setters
    void setMapData(const kernel::MapDisplayDto& data);
    void setAgvListModel(QAbstractListModel* model);
    void setBackgroundColor(const QColor& color);
    void setStationColor(const QColor& color);
    void setPathColor(const QColor& color);
    void setAreaColor(const QColor& color);
    void setStationSize(double size);
    void setPathWidth(double width);
    void setScaleFactor(double factor);
    void setPanOffset(const QPointF& offset);
    void setShowAgvLabels(bool show);
    void setAgvIconSize(double size);
    void setFilterAgvByMap(bool filter);

    // QQuickPaintedItem interface
    void paint(QPainter* painter) override;

    // Mouse/touch interaction support
    Q_INVOKABLE QPointF screenToMap(const QPointF& screenPoint) const;
    Q_INVOKABLE QPointF mapToScreen(const QPointF& mapPoint) const;
    Q_INVOKABLE void resetView();
    Q_INVOKABLE void fitToView();

    
    // Map initialization (matching reference implementation)
    Q_INVOKABLE bool initMap(const QString& mapName);

    // Center view on a specific map point
    Q_INVOKABLE void centerOnPoint(const QPointF& mapPoint, double scale = -1);

protected:
    void mousePressEvent(QMouseEvent* event) override;
    void mouseMoveEvent(QMouseEvent* event) override;
    void mouseReleaseEvent(QMouseEvent* event) override;
    void wheelEvent(QWheelEvent* event) override;

signals:
    void mapDataChanged();
    void agvListModelChanged();
    void backgroundColorChanged();
    void stationColorChanged();
    void pathColorChanged();
    void areaColorChanged();
    void stationSizeChanged();
    void pathWidthChanged();
    void scaleFactorChanged();
    void panOffsetChanged();
    void showAgvLabelsChanged();
    void agvIconSizeChanged();
    void filterAgvByMapChanged();
    void mapWidthChanged();
    void mapHeightChanged();
    void stationClicked(const QString& stationName, const QPointF& position);
    void agvClicked(int agvNumber, const QPointF& position);
    void singleClick(const QPointF& position);

// 移除定时器槽函数

private:
    kernel::MapDisplayDto mapData_;
    QAbstractListModel* agvListModel_{nullptr};

    // 使用配置结构替代分散的成员变量
    MapDrawingConfig config_;

    // 保留一些必要的成员变量用于QML属性绑定
    QPointF panOffset_{0.0, 0.0};               // Pan offset
    int mapWidth_{0};
    int mapHeight_{0};
    bool showAgvLabels_{true};
    double agvIconSize_{40.0};  // AGV图标大小（像素）
    bool filterAgvByMap_{true};

    // Transformation support (matching reference implementation)
    QTransform moveTransform_;       // Base coordinate flip transform (handles axis inversion)
    QTransform scaleTransform_;      // Scale transformation
    QTransform mouseMoveTransform_;  // Pan transformation (mouse drag)
    bool mapLoadSuccess_{false};     // Map load status

    // Mouse interaction state
    QPointF mousePressPos_;
    QPointF lastMousePos_;
    bool isDragging_{false};
    
    // 变换缓存机制
    mutable QHash<int, QPointF> transformedPointsCache_;
    mutable bool cacheValid_{false};
    mutable QTransform lastTransform_;


    // Drawing methods matching reference implementation
    void setupTransforms();
    void drawMapBackground(QPainter* painter);
    void drawBezierPaths(QPainter* painter);
    void drawArcPaths(QPainter* painter);
    void drawStraightPaths(QPainter* painter);
    void drawAdvancedPoints(QPainter* painter);
    void drawNormalPoints(QPainter* painter);
    void drawAdvancedAreas(QPainter* painter);
    void drawAgvLayer(QPainter* painter);  // 新增：绘制AGV层

    // Bezier curve drawing (from reference)
    void drawBezierCurve(QPainter* painter, const QPointF& start, const QPointF& end,
                        const QPointF& control1, const QPointF& control2, const QColor& color);
    
    // 公共绘制工具方法
    QPen createPathPen(const QColor& color, double width = -1, Qt::PenStyle style = Qt::SolidLine) const;
    void setupPainter(QPainter* painter) const;

    // Point transformation utilities (matching reference)
    QPointF pointTransform(const QPointF& point) const;
    QPointF mouseTransformPoint(const QPointF& point) const;
    QColor getStationColorByType(const QString& className, const QString& stationType) const;
    
    // 变换缓存管理
    void invalidateCache() const;
    bool isCacheValid() const;
    QPointF getCachedTransform(int index, const QPointF& originalPoint) const;

    // 安全检查方法
    bool isValidIndex(int index, size_t containerSize) const;
    bool hasValidPoints(const QVector<QPointF>& points) const;
    bool isPointInBounds(const QPointF& point) const;
    
    // 配置管理
    void loadConfig();
    void saveConfig();
    void resetToDefaultConfig();

    // Map position update (matching reference)
    void updateMapPos();
    
    // Settings management (matching reference)
    void saveTransformParams();
    void loadTransformParams();
    
    // Station selection (matching reference)
    void clickStation(const QPointF& pos);
    void clickAgv(const QPointF& pos);  // 新增：AGV点击检测

    // AGV 辅助方法
    QColor getAgvStatusColor(bool isOnline, bool isCharging, bool isControlled,
                             bool isBlocked, bool isLocked) const;
    void drawAgvIcon(QPainter* painter, const QPointF& position, double angle,
                     const QColor& color, double size) const;
    void drawAgvLabel(QPainter* painter, const QPointF& position, const QString& label) const;

    // Property setters for map dimensions
    void setMapWidth(int width);
    void setMapHeight(int height);

    // 连接AGV模型信号
    void connectAgvModelSignals();
    void disconnectAgvModelSignals();

    void rebuildBaseTransform();
};

} // namespace presentation
